package com.jic.member.impl;

import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.RestResult;
import com.jic.member.constant.consist.ResponseCode;
import com.jic.member.exception.AppRuntimeException;
import com.jic.member.mapper.TLabelMapper;
import com.jic.member.mapper.TLabelMemberRelationMapper;
import com.jic.member.entity.TLabel;
import com.jic.member.entity.TLabelMemberRelation;
import com.jic.member.request.TLabelMemberRelationRequest;
import com.jic.member.response.TLabelMemberListResponse;
import com.jic.member.response.TLabelMemberNewResponse;
import com.jic.member.response.TLabelMemberOneResponse;
import com.jic.member.response.TLabelMemberResponse;
import com.jic.member.service.TLabelMemberRelationService;
import com.jic.manager.api.manage.SysDeptApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 接口实现类
 *
 * @author : 建投数据科技(山东)有限公司
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class TLabelMemberRelationServiceImpl implements TLabelMemberRelationService {

    @Resource
    private TLabelMemberRelationMapper mapper;
    @Resource
    private SysDeptApi sysDeptApi;
    @Resource
    private TLabelMapper labelMapper;

    /**
     * 新增记录
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存成功
     */
    @Override
    public int save(TLabelMemberRelation request) {
        int flag = mapper.insert(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
        }
    }


    /**
     * 保存或修改记录信息
     *
     * @param request 需要保存的入参实体类
     * @return int 是否保存或修改成功
     * author 建投数据科技(山东)有限公司
     * @date 2020-3-11 20:54:09
     */
    @Override
    public int saveOrUpdate(TLabelMemberRelation request) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.updateByPrimaryKey(request);
                if (flag == 1) {
                    return 1;
                }
            } else {
                log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.insertSelective(request);
                if (flag == 1) {
                    return 1;
                } else {
                    throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改失败");
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "用户保存或修改失败");
        }
        return -1;
    }

    /**
     * 删除记录
     *
     * @param request 需要删除,含有主键的入参实体类
     * @return int 是否删除成功
     */
    @Override
    public int deleteByPrimaryKey(TLabelMemberRelation request) {
        int flag = mapper.deleteByPrimaryKey(request);
        if (flag == 1) {
            return 1;
        } else {
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
        }
    }


    /**
     * 修改
     *
     * @param request
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(TLabelMemberRelation request) {
        try {
            log.info("修改记录");
            TLabelMemberRelation param = new TLabelMemberRelation();
            BeanUtils.copyProperties(request, param);
            int flag = mapper.updateByPrimaryKeySelective(param);
            if (flag == 1) {
                return 1;
            } else {
                throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
            }
        } catch (Exception e) {
            log.error("修改记录失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
        }

    }

    /**
     * 记录详情
     *
     * @param request 查询的入参实体类
     * @return 数据库查询到的实体类
     */
    @Override
    public TLabelMemberRelation getByPrimaryKey(TLabelMemberRelation request) {
        return mapper.selectByPrimaryKey(request);
    }


    /**
     * 不分页查询
     *
     * @param request 不分页查询入参实体类
     * @return 数据库查到的实体类列表
     */
    @Override
    public List<TLabelMemberRelation> listAllRecord(TLabelMemberRelation request) {
        return mapper.selectBySelective(request);
    }

    /**
     * 通过标签ID查询会员
     *
     * @param tLabelMemberRelationRequest
     */
    @Override
    public void getMemberByLabelId(TLabelMemberRelationRequest tLabelMemberRelationRequest) {
        //根据标签查询会员
        List<String> memberIdList = mapper.queryBatchByLabelIds(tLabelMemberRelationRequest);
    }

    /**
     * 通过用户ids查询标签
     *
     * @param request
     * @return
     */
    @Override
    public RestResult<List<TLabelMemberListResponse>> queryLabelByThirdUserId(TLabelMemberRelationRequest request) {
        List<TLabelMemberListResponse> responseList = new ArrayList<>();
        if (request.getDeptIds() != null && request.getDeptIds().length > 0) {
            for (int i = 0; i < request.getDeptIds().length; i++) {
                TLabelMemberListResponse tLabelMemberNewResponse = assemblyData(request.getDeptIds()[i], request.getThirdUserId());
                responseList.add(tLabelMemberNewResponse);
            }
        } else {
            TLabelMemberListResponse tLabelMemberNewResponse = assemblyData(request.getAdminOperate().getDeptId(),
                    request.getThirdUserId());
            responseList.add(tLabelMemberNewResponse);
        }

        return RestResult.success(responseList);
    }

    /**
     * 组装数据
     *
     * @param deptId
     * @return
     */
    private TLabelMemberListResponse assemblyData(Long deptId, String thirdUserId) {
        TLabelMemberListResponse tLabelMemberListResponse = new TLabelMemberListResponse();
        //通过组织ID查询组织名称
        RestResult<String> stringRestResult = sysDeptApi.queryDeptNameById(deptId);
        tLabelMemberListResponse.setDeptName(stringRestResult.getData());
        tLabelMemberListResponse.setDeptId(deptId);
        //查询组织一级标签
        TLabel tLabel = new TLabel();
        tLabel.setDeptId(deptId);
        tLabel.setLabelGrade(1L);
        List<TLabel> tLabelList = labelMapper.selectBySelective(tLabel);
        List<TLabelMemberOneResponse> memberOneResponseList = new ArrayList<>();
        for (TLabel tLabel1 : tLabelList) {
            TLabelMemberOneResponse tLabelMemberOneResponse = new TLabelMemberOneResponse();

            if (StringUtils.equals(tLabel1.getLabelName(), "事实属性")) {
                tLabelMemberOneResponse.setLabelId(tLabel1.getId());
                tLabelMemberOneResponse.setLabelName("基础信息");
                tLabelMemberOneResponse.setLabelMemberType(1);
            }
            //查询二级标签
            tLabel = new TLabel();
            tLabel.setPid(tLabel1.getId());
            List<TLabel> tLabelList1 = labelMapper.selectBySelective(tLabel);
            List<TLabelMemberNewResponse> labelMemberTwoResponseList = new ArrayList<>();
            for (TLabel tLabel2 : tLabelList1) {
                //查询三级标签
                tLabel = new TLabel();
                tLabel.setPid(tLabel2.getId());
                List<TLabel> tLabelList2 = labelMapper.selectBySelective(tLabel);
                List<TLabelMemberNewResponse> tLabelMemberThreeResponseList = new ArrayList<>();
                for (TLabel tLabel3 : tLabelList2) {
                    TLabelMemberNewResponse tLabelMemberNewResponse1 = new TLabelMemberNewResponse();
                    //查询会员关联标签
                    TLabelMemberRelation tLabelMemberRelation = new TLabelMemberRelation();
                    tLabelMemberRelation.setDeptId(deptId);
                    tLabelMemberRelation.setLabelId(tLabel3.getId());
                    tLabelMemberRelation.setMemberId(thirdUserId);
                    TLabelMemberResponse tLabelMemberResponse = mapper.queryLabelInfo(tLabelMemberRelation);
                    if (tLabelMemberResponse != null) {
                        tLabelMemberNewResponse1.setLabelId(tLabelMemberResponse.getLabelId());
                        tLabelMemberNewResponse1.setLabelName(tLabelMemberResponse.getLabelName());
                        tLabelMemberThreeResponseList.add(tLabelMemberNewResponse1);
                    }
                }
                if (CollectionUtils.isNotEmpty(tLabelMemberThreeResponseList)) {
                    //二级标签
                    TLabelMemberNewResponse tLabelMemberNewResponse = new TLabelMemberNewResponse();
                    tLabelMemberNewResponse.setLabelId(tLabel2.getId());
                    tLabelMemberNewResponse.setLabelName(tLabel2.getLabelName());
                    labelMemberTwoResponseList.add(tLabelMemberNewResponse);
                    tLabelMemberNewResponse.setTLabelMemberThreeResponseList(tLabelMemberThreeResponseList);
                }
            }
            if (CollectionUtils.isNotEmpty(labelMemberTwoResponseList)) {
                tLabelMemberOneResponse.setLabelMemberTwoResponseList(labelMemberTwoResponseList);
            }
            memberOneResponseList.add(tLabelMemberOneResponse);
        }
        //查询自定义标签
        TLabel tLabel1 = new TLabel();
        tLabel1.setDeptId(deptId);
        tLabel1.setLabelType(2);
        List<TLabel> tLabelList1 = labelMapper.selectBySelective(tLabel1);
        if (CollectionUtils.isNotEmpty(tLabelList1)) {
            TLabelMemberOneResponse tLabelMemberOneResponse = new TLabelMemberOneResponse();
            tLabelMemberOneResponse.setLabelName("自定义标签");
            tLabelMemberOneResponse.setLabelMemberType(6);
            List<TLabelMemberNewResponse> labelMemberTwoResponseList = new ArrayList<>();
            for (TLabel tLabel2 : tLabelList1) {
                TLabelMemberNewResponse tLabelMemberNewResponse = new TLabelMemberNewResponse();
                tLabelMemberNewResponse.setLabelName(tLabel2.getLabelName());
                tLabelMemberNewResponse.setLabelId(tLabel2.getId());
                labelMemberTwoResponseList.add(tLabelMemberNewResponse);
            }
            if (CollectionUtils.isNotEmpty(labelMemberTwoResponseList)) {
                tLabelMemberOneResponse.setLabelMemberTwoResponseList(labelMemberTwoResponseList);
            }
            memberOneResponseList.add(tLabelMemberOneResponse);
        }
        tLabelMemberListResponse.setMemberOneResponseList(memberOneResponseList);
        return tLabelMemberListResponse;
    }


}
